//
//  LocationDetailsViewController.swift
//  MyLocations
//
//  Created by JokerAtBaoFeng on 16/3/16.
//  Copyright © 2016年 baofeng. All rights reserved.
//

import UIKit
import CoreLocation
import CoreData

private let dateFormatter: NSDateFormatter = {
    let formatter = NSDateFormatter()
    formatter.dateStyle = .MediumStyle
    formatter.timeStyle = .ShortStyle
    print("Formatter only apperance once!")
    return formatter
}()

class LocationDetailsViewController: UITableViewController {
    
    //MARK: Other Data Variables Definitions
    var coordinate = CLLocationCoordinate2D(latitude: 0, longitude: 0)
    var placemark: CLPlacemark?
    
    var descriptionText = ""
    
    var categoryName = "No Category"
    
    var managedObjectContext: NSManagedObjectContext!
    
    var date = NSDate()
    
    var locationToEdit: MyLocationLocation? {
        didSet {
            if let location = locationToEdit {
                descriptionText = location.locationDescription!
                categoryName = location.category!
                date = location.date
                coordinate = CLLocationCoordinate2DMake(location.latitude, location.longitude)
                placemark = location.placemark
            }
        }
    }
    
    var image: UIImage? {
        didSet{
            if let image = image {
                self.showImage(image)
            }
        }
    }
    
    var observer: AnyObject!
    
    //MARK: UI Controll Outlets Definitions
    @IBOutlet weak var descriptionTextview: UITextView!
    
    @IBOutlet weak var categoryLabel: UILabel!
    
    @IBOutlet weak var latitudeLabel: UILabel!
    
    @IBOutlet weak var longitudeLabel: UILabel!
    
    @IBOutlet weak var addressLabel: UILabel!
    
    @IBOutlet weak var addressLbl: UILabel!
    @IBOutlet weak var dateLabel: UILabel!
    
    @IBOutlet weak var addPhotoLabel: UILabel!
    
    @IBOutlet weak var imageView: UIImageView!
    //MARK: UI Controller Events Handlers
    
    @IBAction func cancel()
    {
        dismissViewControllerAnimated(true, completion: nil)
    }
    @IBAction func done() {
        print(descriptionText)
        let hudView = HUDView.hudInView(navigationController!.view, animated: true)
        
        var location: MyLocationLocation
        if let temp = locationToEdit {
            hudView.text = "Updated"
            location = temp
        }else{
            hudView.text = "Tagged"
            location = NSEntityDescription.insertNewObjectForEntityForName("Location", inManagedObjectContext: managedObjectContext) as! MyLocationLocation
            
            location.photoID = nil
        }
        
        location.locationDescription = descriptionText
        location.category = categoryName
        location.latitude = coordinate.latitude
        location.longitude = coordinate.longitude
        location.date = date
        location.placemark = placemark
        
        if let image = image {
            if !location.hasPhoto {
                location.photoID = MyLocationLocation.nextPhotoID()
            }
            
            let data =  UIImageJPEGRepresentation(image, 0.5)
            do{
                try data?.writeToFile(location.photoPath, options: .DataWritingAtomic)
            }catch let error as NSError {
                print("Error writing file: \(error)")
            }
        }
        
        
        do{
            try managedObjectContext.save()
        }catch let error as NSError {
            print("Error: \(error)")
            fatalCoreDataError(error)
            return
        }
        
        let delayInSecond = 0.6
        afterDelay(delayInSecond){
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
    //MARK: TabelView Delegate Functions
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView.backgroundColor = UIColor.blackColor()
        
        tableView.separatorColor = UIColor(white: 1.0, alpha: 0.2)
        
        tableView.indicatorStyle = .White
        
        descriptionTextview.textColor = UIColor.whiteColor()
        descriptionTextview.backgroundColor = UIColor.blackColor()
        
        addPhotoLabel.textColor = UIColor.whiteColor()
        addPhotoLabel.highlightedTextColor = addPhotoLabel.textColor
        
        addressLabel.textColor = UIColor(white: 1.0, alpha: 0.4)
        addressLabel.highlightedTextColor = addressLabel.textColor
        
        listenForBackgroundNotification()
        
        if let location = locationToEdit {
            title = "Edit Location"
            if location.hasPhoto {
                if let image = location.photoImage {
                    showImage(image)
                }
            }
        }
        
        descriptionTextview.text = descriptionText
        categoryLabel.text = categoryName
        
        latitudeLabel.text = String(format: "%.8f", coordinate.latitude)
        longitudeLabel.text = String(format: "%.8f", coordinate.longitude)
        
        if let placemark = placemark {
            addressLabel.text = stringFromPlacemark(placemark)
        }else{
            addressLabel.text = "No Address Found"
        }
        
        dateLabel.text = formatDate(date)
        
        let gestureRecognizer = UITapGestureRecognizer(target: self, action: Selector("hideKeyboard:"))
        gestureRecognizer.cancelsTouchesInView = false
        tableView.addGestureRecognizer(gestureRecognizer)
    }
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        switch (indexPath.section, indexPath.row){
            
        case (0,0):
            return 88
        case (1,_):
            return imageView.hidden ? 44 : 280
        case (2,2):
            addressLabel.frame.size = CGSize(width: view.bounds.size.width - 115, height: 10000)
            addressLabel.sizeToFit()
            addressLabel.frame.origin.x = view.bounds.size.width - addressLabel.frame.width - 15
            return addressLabel.frame.size.height + 20
        default:
            return 44
        }
    }
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "PickerCategory" {
            let controller = segue.destinationViewController as! CategoryPickerViewController
            controller.selectedCategoryName = categoryName
            
        }
    }
    
    @IBAction func categoryPickerDidPickedCategory(segue: UIStoryboardSegue)
    {
        let controller = segue.sourceViewController as! CategoryPickerViewController
        
        categoryName = controller.selectedCategoryName
        categoryLabel.text = categoryName
        
    }
    
    
    override func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
        if indexPath.section == 0 || indexPath.section == 1 {
            return indexPath
        }else{
            return nil
        }
    }
    
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.section == 0 && indexPath.row == 0 {
            descriptionTextview.becomeFirstResponder()
        }else if indexPath.section == 1 && indexPath.row == 0 {
            tableView.deselectRowAtIndexPath(indexPath, animated: true)
            pickPhoto()
        }
    }
    
    override  func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.backgroundColor = UIColor.blackColor()
        
        if let textLabel = cell.textLabel {
            textLabel.textColor = UIColor.whiteColor()
            textLabel.highlightedTextColor = textLabel.textColor
        }
        
        if let detailLabel = cell.detailTextLabel {
            detailLabel.textColor = UIColor(white: 1.0, alpha: 0.4)
            detailLabel.highlightedTextColor = detailLabel.textColor
        }
        
        let selectionView = UIView(frame: CGRect.zero)
        selectionView.backgroundColor = UIColor(white: 1.0, alpha: 0.2)
        cell.selectedBackgroundView = selectionView
        
        if indexPath.row == 2{
            let addressLbl = cell.viewWithTag(100) as! UILabel
            addressLbl.textColor = UIColor.whiteColor()
            addressLabel.highlightedTextColor = addressLbl.textColor
        }
        
    }
    
    deinit{
        print("*** deinit \(self)")
        NSNotificationCenter.defaultCenter().removeObserver(observer)
    }
    
    //MARK: Other functions
    func listenForBackgroundNotification(){
        observer = NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidEnterBackgroundNotification, object: nil, queue: NSOperationQueue.mainQueue(), usingBlock: {
            [weak self] notification in
            if let strongSelf = self {
                if strongSelf.presentedViewController != nil {
                    strongSelf.dismissViewControllerAnimated(true, completion: nil)
                }
                strongSelf.descriptionTextview.resignFirstResponder()
            }
            })
    }
    
    func showImage(image: UIImage){
        imageView.image = image
        imageView.hidden = false
        imageView.frame = CGRect(x:10, y:10, width: 260, height: 260)
        addPhotoLabel.hidden = true
    }
    
    func stringFromPlacemark(placemark: CLPlacemark) -> String
    {
        var line: String = "";
        
        line.addText(placemark.subThoroughfare)
        
        line.addText(placemark.thoroughfare, withSeparator: " ")
        
        line.addText(placemark.locality, withSeparator: ", ")
        
        line.addText(placemark.administrativeArea, withSeparator: ", ")
        
        line.addText(placemark.postalCode, withSeparator: " ")
        
        line.addText(placemark.country, withSeparator: ", ")
        
        return line
        
    }
    
    func formatDate(date: NSDate) -> String
    {
        return dateFormatter.stringFromDate(date)
    }
    //MARK: TextView Delegate
    
}

extension LocationDetailsViewController: UITextViewDelegate {
    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        descriptionText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
        return true
    }
    func textViewDidEndEditing(textView: UITextView) {
        descriptionText = textView.text
    }
    
    //MARK: Gesture handler
    func hideKeyboard(gesture: UIGestureRecognizer)
    {
        let point = gesture.locationInView(tableView)
        let indexPath = tableView.indexPathForRowAtPoint(point)
        if indexPath != nil && indexPath?.section == 0
            && indexPath?.row == 0 {
                return
        }
        descriptionTextview.resignFirstResponder()
    }
}


extension LocationDetailsViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func pickPhoto()
    {
        if UIImagePickerController.isSourceTypeAvailable(.Camera) {
            showPhotoMenu()
        }else{
            choosePhotoFromLibrary()
        }
    }
    
    func showPhotoMenu()
    {
        let alertController = UIAlertController(title: nil, message: nil, preferredStyle: .ActionSheet)
        let cancelAction = UIAlertAction(title: "Cancle", style:.Cancel, handler: nil)
        alertController.addAction(cancelAction)
        
        let takePhotoAction = UIAlertAction(title: "Take Photo", style: .Default, handler: {
            _ in
            self.takePhotoWithCamer()
        })
        alertController.addAction(takePhotoAction)
        
        let chooseFromLibraryAction = UIAlertAction(title: "Choose From Library", style: .Default, handler: {
            _ in
            self.choosePhotoFromLibrary()
        })
        alertController.addAction(chooseFromLibraryAction)
        
        presentViewController(alertController, animated: true, completion: nil)
        
    }
    
    func choosePhotoFromLibrary(){
        let imagePicker = MyImagePickerController()
        imagePicker.view.tintColor = view.tintColor
        imagePicker.sourceType = .PhotoLibrary
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    
    func takePhotoWithCamer(){
        let imagePicker = UIImagePickerController()
        imagePicker.sourceType = .Camera
        imagePicker.delegate = self
        imagePicker.allowsEditing = true
        presentViewController(imagePicker, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        image = info[UIImagePickerControllerEditedImage] as! UIImage?
        
        tableView.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        dismissViewControllerAnimated(true, completion: nil)
    }
}
